#include <iostream>
#include <memory>
#include <string>
#include <typeinfo>
#include <unordered_map>

// 假设所有工厂返回 Base*
struct Base {
    virtual void hello() = 0;
};

struct Derived : Base {
    void hello() override { std::cout << "I'm Derived\n"; }
};

// 工厂函数
using Factory = Base* (*)();
using FactoryMap = std::unordered_map<std::string, Factory>;

// 全局存放 (基类名字 → 工厂表)
std::unordered_map<std::string, FactoryMap> g_factory_maps;

FactoryMap& GetClassFactoryMapByBaseClass(const std::string& baseName)
{
    return g_factory_maps[baseName]; // 自动创建或返回已有
}

// 注册派生类
void Register()
{
    FactoryMap& map = GetClassFactoryMapByBaseClass(typeid(Base).name());
    map[typeid(Derived).name()] = []() -> Base* { return new Derived(); };
}

// 使用
int main()
{
    Register();

    FactoryMap& map = GetClassFactoryMapByBaseClass(typeid(Base).name());
    auto it = map.find(typeid(Derived).name());
    if (it != map.end()) {
        std::unique_ptr<Base> obj(it->second());
        obj->hello();
    }
}
